package com.android.jingweiapp.fragment.information;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.SwipeRefreshLayout;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.android.jingweiapp.R;
import com.android.jingweiapp.XMLPhase.HomeNewsXMLPhase;
import com.android.jingweiapp.activity.DetailTextActivity;
import com.android.jingweiapp.activity.NewsDetailPicActivity;
import com.android.jingweiapp.activity.NewsDetailVideoActivity;
import com.android.jingweiapp.activity.SearchActivity;
import com.android.jingweiapp.adapter.CommonAdapter;
import com.android.jingweiapp.adapter.ImageAdapter;
import com.android.jingweiapp.bean.NewsBean;
import com.android.jingweiapp.bean.PicBean;
import com.android.jingweiapp.util.CommonUtil;
import com.android.jingweiapp.util.Contacts;
import com.android.jingweiapp.util.HttpUtil;
import com.android.jingweiapp.widget.ListViewForScrollView;
import com.android.jingweiapp.widget.MyToast;
import com.facebook.drawee.view.SimpleDraweeView;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

import butterknife.Bind;
import butterknife.ButterKnife;

/**
 * 首页
 */
public class HomeNewsFragment extends Fragment {

    @Bind(R.id.et_search)
    EditText etSearch;
    @Bind(R.id.btn_search)
    TextView btnSearch;
    @Bind(R.id.viewpager)
    public ViewPager viewpager;
    @Bind(R.id.tv_title_top)
    TextView tvTitleTop;
    @Bind(R.id.list_important_news)
    ListViewForScrollView listImportantNews;
    @Bind(R.id.ly_top)
    RelativeLayout lyTop;
    @Bind(R.id.ly_refresh)
    SwipeRefreshLayout lyRefresh;
    @Bind(R.id.viewpager_title)
    TextView viewpagerTitle;
    @Bind(R.id.viewpager_num)
    TextView viewpagerNum;

    private ArrayList<PicBean> picBeans;
    private NewsBean topNews;
    private ArrayList<NewsBean> newsBeans;
    private CommonAdapter adapter;

    private ArrayList<SimpleDraweeView> draweeViews;
    private ImageAdapter imageAdapter;
    private int currentItem = 0;
    private ScheduledExecutorService scheduledExecutorService;
    //轮播图图片数量
    private final static int IMAGE_COUNT = 6;
    //自动轮播启用开关
    private final static boolean isAutoPlay = true;

    public Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 0:
                    dealData((String) msg.obj);
                    lyRefresh.setRefreshing(false);
                    break;
                case 1:
                    MyToast.getInstance().show("出错了，请刷新重试");
                    lyRefresh.setRefreshing(false);
                    break;
                case 2:
                    viewpager.setCurrentItem(currentItem);
            }
        }
    };

    public HomeNewsFragment() {

    }


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_home_news, container, false);
        ButterKnife.bind(this, view);
        init();
        getData();
        return view;
    }

    public void init() {
        picBeans = new ArrayList<>();
        topNews = new NewsBean();
        newsBeans = new ArrayList<>();

        adapter = new CommonAdapter(newsBeans, getActivity());
        listImportantNews.setAdapter(adapter);

        listImportantNews.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (newsBeans.get(position).getType() == Contacts.NEWS_TYPE.ANNOUNCE
                        || newsBeans.get(position).getType() == Contacts.NEWS_TYPE.IMPORTANT_NEWS
                        || newsBeans.get(position).getType() == Contacts.NEWS_TYPE.JX_DYNMIC
                        || newsBeans.get(position).getType() == Contacts.NEWS_TYPE.NOTIFICATION
                        || newsBeans.get(position).getType() == Contacts.NEWS_TYPE.QW_DYNAMIC
                        || newsBeans.get(position).getType() == Contacts.NEWS_TYPE.JX_TOP) {
                    startActivity(new Intent(getActivity(), DetailTextActivity.class)
                            .putExtra(Contacts.KEY.KEY_OBJECT, newsBeans.get(position))
                            .putExtra(Contacts.KEY.KEY_TYPE, Contacts.TYPE.TEXT_NEWS));
                } else if (newsBeans.get(position).getType() == Contacts.NEWS_TYPE.PIC_NEWS) {
                    startActivity(new Intent(getActivity(), NewsDetailPicActivity.class)
                            .putExtra(Contacts.KEY.KEY_OBJECT, newsBeans.get(position))
                            .putExtra(Contacts.KEY.KEY_TYPE, Contacts.TYPE.TEXT_NEWS));
                } else if (newsBeans.get(position).getType() == Contacts.NEWS_TYPE.VIDEO_NEWS) {
                    startActivity(new Intent(getActivity(), NewsDetailVideoActivity.class)
                            .putExtra(Contacts.KEY.KEY_OBJECT, newsBeans.get(position))
                            .putExtra(Contacts.KEY.KEY_TYPE, Contacts.TYPE.TEXT_NEWS));
                }
            }
        });

        lyRefresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                getData();
            }
        });
        btnSearch.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getActivity(), SearchActivity.class);
                String str = etSearch.getText().toString();
                intent.putExtra(Contacts.KEY.SEARCH_KEYWORD, TextUtils.isEmpty(str) ? " " : str);
                startActivity(intent);
            }
        });

        draweeViews = new ArrayList<>();
        imageAdapter = new ImageAdapter(draweeViews);
        viewpager.setAdapter(imageAdapter);
        viewpager.addOnPageChangeListener(new MyPageChangeListener());
    }

    public void getData() {
        lyRefresh.setRefreshing(true);
        new Thread() {
            @Override
            public void run() {
                String result = HttpUtil.postWithContent(Contacts.BASE_URL,
                        HomeNewsXMLPhase.createParam(getActivity()),
                        new HomeNewsXMLPhase());
                if (TextUtils.isEmpty(result)) {
                    handler.obtainMessage(1).sendToTarget();
                } else {
                    Message message = handler.obtainMessage();
                    message.what = 0;
                    message.obj = result;
                    handler.sendMessage(message);
                }
            }
        }.start();

    }

    public void dealData(String result) {
        try {
            JSONObject jsonObject = new JSONObject(result);
            JSONArray array = jsonObject.getJSONArray(Contacts.KEY.KEY_PIC);
            for (int i = 0; i < array.length(); i++) {
                picBeans.add(new PicBean(array.getJSONObject(i)));
            }
            topNews = new NewsBean(jsonObject.getJSONArray(Contacts.KEY.KEY_TOP).getJSONObject(0));

            JSONArray array1 = jsonObject.getJSONArray(Contacts.KEY.KEY_LIST);
            newsBeans.clear();
            for (int i = 0; i < array1.length(); i++) {
                newsBeans.add(new NewsBean(array1.getJSONObject(i)));
            }

            setPic();
            setTop();
            adapter.notifyDataSetChanged();
        } catch (JSONException e) {
            e.printStackTrace();
        }

    }

    /**
     * 设置头条信息
     */
    public void setTop() {
        tvTitleTop.setText(topNews.getTitle());
        lyTop.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(getActivity(), DetailTextActivity.class)
                        .putExtra(Contacts.KEY.KEY_OBJECT, topNews));
            }
        });
    }

    public void setPic() {
        for (int i = 0; i < IMAGE_COUNT; i++) {
            SimpleDraweeView simpleDraweeView = (SimpleDraweeView) LayoutInflater.from(getActivity()).inflate(R.layout.item_adver, null);
            CommonUtil.loadPic(Uri.parse(Contacts.BASE_PIC_URL + picBeans.get(i).getPicUrl()), simpleDraweeView);
            final int finalI = i;
            simpleDraweeView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (newsBeans.get(finalI).getType() == Contacts.NEWS_TYPE.ANNOUNCE
                            || newsBeans.get(finalI).getType() == Contacts.NEWS_TYPE.IMPORTANT_NEWS
                            || newsBeans.get(finalI).getType() == Contacts.NEWS_TYPE.JX_DYNMIC
                            || newsBeans.get(finalI).getType() == Contacts.NEWS_TYPE.NOTIFICATION
                            || newsBeans.get(finalI).getType() == Contacts.NEWS_TYPE.QW_DYNAMIC
                            || newsBeans.get(finalI).getType() == Contacts.NEWS_TYPE.JX_TOP) {
                        startActivity(new Intent(getActivity(), DetailTextActivity.class)
                                .putExtra(Contacts.KEY.KEY_OBJECT, newsBeans.get(finalI))
                                .putExtra(Contacts.KEY.KEY_TYPE, Contacts.TYPE.TEXT_NEWS));
                    } else if (newsBeans.get(finalI).getType() == Contacts.NEWS_TYPE.PIC_NEWS) {
                        startActivity(new Intent(getActivity(), NewsDetailPicActivity.class)
                                .putExtra(Contacts.KEY.KEY_OBJECT, newsBeans.get(finalI))
                                .putExtra(Contacts.KEY.KEY_TYPE, Contacts.TYPE.TEXT_NEWS));
                    } else if (newsBeans.get(finalI).getType() == Contacts.NEWS_TYPE.VIDEO_NEWS) {
                        startActivity(new Intent(getActivity(), NewsDetailVideoActivity.class)
                                .putExtra(Contacts.KEY.KEY_OBJECT, newsBeans.get(finalI))
                                .putExtra(Contacts.KEY.KEY_TYPE, Contacts.TYPE.TEXT_NEWS));
                    }
                }
            });
            draweeViews.add(simpleDraweeView);
        }
        imageAdapter.notifyDataSetChanged();
        startPlay();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
        stopPlay();
    }

    /**
     * 开始轮播图切换
     */
    private void startPlay() {
        scheduledExecutorService = Executors.newSingleThreadScheduledExecutor();
        scheduledExecutorService.scheduleAtFixedRate(new SlideShowTask(), 1, 4, TimeUnit.SECONDS);
    }

    /**
     * 停止轮播图切换
     */
    private void stopPlay() {
        if (scheduledExecutorService != null) {
            scheduledExecutorService.shutdown();
        }
    }


    /**
     * ViewPager的监听器
     * 当ViewPager中页面的状态发生改变时调用
     *
     * @author caizhiming
     */
    private class MyPageChangeListener implements ViewPager.OnPageChangeListener {
        boolean isAutoPlay = false;

        @Override
        public void onPageScrollStateChanged(int arg0) {
            switch (arg0) {
                case 1:// 手势滑动，空闲中
                    isAutoPlay = false;
                    break;
                case 2:// 界面切换中
                    isAutoPlay = true;
                    break;
                case 0:
                    // 滑动结束，即切换完毕或者加载完毕
                    // 当前为最后一张，此时从右向左滑，则切换到第一张
                    if (viewpager.getCurrentItem() == viewpager.getAdapter().getCount() - 1 && !isAutoPlay) {
                        viewpager.setCurrentItem(0);
                    }
                    // 当前为第一张，此时从左向右滑，则切换到最后一张
                    else if (viewpager.getCurrentItem() == 0 && !isAutoPlay) {
                        viewpager.setCurrentItem(viewpager.getAdapter().getCount() - 1);
                    }
                    break;
            }
        }

        @Override
        public void onPageScrolled(int arg0, float arg1, int arg2) {
        }

        @Override
        public void onPageSelected(int pos) {
            currentItem = pos;
            viewpagerTitle.setText(picBeans.get(pos).getTitle());
            viewpagerNum.setText(String.format("%d/%d", pos + 1, IMAGE_COUNT));

        }

    }


    /**
     * 执行轮播图切换任务
     *
     * @author caizhiming
     */
    private class SlideShowTask implements Runnable {

        @Override
        public void run() {
// TODO Auto-generated method stub
            synchronized (viewpager) {
                currentItem = (currentItem + 1) % draweeViews.size();
                handler.obtainMessage(2).sendToTarget();
            }
        }
    }
}
